<template>
  <div>
    <el-checkbox-group v-model="roleIds">
      <el-checkbox v-for="role in list" :key="role.id" :label="role.id">{{ role.name }}</el-checkbox>
      <!-- <el-checkbox label="3">开发者</el-checkbox>
      <el-checkbox label="2">人事</el-checkbox> -->
    </el-checkbox-group>
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="addFn">确定</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getRoles } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
import { assignRoles } from '@/api/employees'
export default {
  props: {
    curId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [], // 所有的角色
      roleIds: [] // 保存当前选中项的id
    }
  },
  watch: { // 监听curId的变化
    curId(newVal, oldVal) {
      this.loadUser()
    }
  },
  created() {
    // 1.取出角色
    this.loadRoles()
    // 2. 取出当前用户已经有的角色
    this.loadUser()
  },
  methods: {
    async loadUser() {
      const res = await getUserDetailById(this.curId)
      console.log('当前已经获取到的用户角色是', res)
      this.roleIds = res.data.roleIds
    },
    // 获取所有的角色数据
    async loadRoles() {
      const res = await getRoles({ page: 1, pagesize: 100 })
      console.log('所有的角色数据是', res)
      this.list = res.data.rows
    },
    // 保存当前角色的信息
    async addFn() {
      const res = await assignRoles({ id: this.curId, roleIds: this.roleIds })
      console.log(res)
      // 1 提示信息
      this.$message.success('分配角色成功')
      // 2 关闭弹层
      this.closeDialog()
    },
    closeDialog() {
      // 1 清空当前选中项的id
    //   this.roleIds = []
      // 2 取消弹层
      this.$emit('close-dialog')
    }
  }
}
</script>
